import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from '@/views/Home.vue';
import Login from '@/views/Login.vue';
import Welcome from '@/views/Welcome.vue';
import Users from '@/views/Users.vue';
import Rights from '@/views/Rights.vue';
import Roles from '@/views/Roles.vue';
import GoodsCate from '@/views/GoodsCate.vue';
import GoodsList from '@/views/GoodsList.vue';
import GoodsParams from '@/views/GoodsParams.vue';
import GoodsAdd from '@/views/GoodsAdd.vue';

Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    redirect: '/welcome',
    children: [
      { path: '/welcome', name: 'Welcome', component: Welcome },
      { path: '/users', name: 'Users', component: Users },
      { path: '/rights', name: 'Rights', component: Rights },
      { path: '/roles', name: 'Roles', component: Roles },
      { path: '/categories', name: 'GoodsCate', component: GoodsCate },
      { path: '/goods', name: 'GoodsList', component: GoodsList },
      { path: '/params', name: 'GoodsParams', component: GoodsParams },
      { path: '/goods/add', name: 'GoodsAdd', component: GoodsAdd },
    ],
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
  },
];

const router = new VueRouter({
  routes,
});

// to: 去哪里？
// from: 从哪里来？
// next: 通关文牒
// 全局前置路由守卫，所有路由在跳转时，都会先经过这个关卡
router.beforeEach((to, from, next) => {
  if (to.path === '/login') {
    next();
  } else {
    const token = localStorage.getItem('token');
    if (token) {
      next();
    } else {
      next('/login');
    }
  }
});

export default router;
